package me.ywy.dbtest.dongnaodb.db;

import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

import java.io.File;

/**
 * Created by ywy on 2018/4/21.
 */
public class BaseDaoFactory {

    private SQLiteDatabase sqLiteDatabase;
    private String sqlDataBaseDir;
    private String sqlDataBasePath;
    private static BaseDaoFactory baseDaoFactory = new BaseDaoFactory();

    public static BaseDaoFactory getInstance(){
        return baseDaoFactory;
    }

    private BaseDaoFactory(){
        sqlDataBaseDir = Environment.getExternalStorageDirectory().getAbsolutePath()+"/ywy";
        File dir = new File(sqlDataBaseDir);
        if(!dir.exists()){
            dir.mkdir();
        }
        sqlDataBasePath = sqlDataBaseDir + "/" + "dongnao_ywy.db";
        sqLiteDatabase = SQLiteDatabase.openOrCreateDatabase(sqlDataBasePath, null);

    }

    public synchronized <M extends BaseDao<T>,T> M getBaseDao(Class<M> daoClass ,  Class<T> entityClass){
        BaseDao baseDao = null;
        try {
            baseDao = daoClass.newInstance();
            baseDao.init(sqLiteDatabase , entityClass);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return (M)baseDao;
    }
}
